import { Button, message, Modal, Select } from 'antd';
import { connect } from 'dva';
import React from 'react';
import enums from '../enums';
import styles from './index.less';

const { Option } = Select;

@connect(state => ({}))
export default class EditModal extends React.PureComponent {
  state = {
    riskEventList: [],
    riskEventUuid: null,
    riskEventType: null,
    keyWords: [],
    msg: null,
    warnMsg: null,
    submitBtnLoading: false,
  };

  componentDidMount() {
    const { editModalData } = this.props;
    this.handleGeriskEventList();
    const riskEventKey = Object.keys(enums.riskEventType).find(
      item => enums.riskEventType[item].value === editModalData.riskEventType,
    );
    this.setState(
      {
        riskEventUuid: editModalData.riskEventUuid,
        riskEventType: editModalData.riskEventType,
        keyWords: enums.riskEventType[riskEventKey].keyWords,
        msg: enums.riskEventType[riskEventKey].msg,
        warnMsg: editModalData.riskWarnMsg,
      },
      () => {
        const ele = document.getElementById('text-area1');
        const ele2 = document.getElementById('text-area2');
        const ele3 = document.getElementById('text-Content');
        const newHtml = this.handleHtml(editModalData.riskWarnMsg);
        ele.innerHTML = editModalData.riskWarnMsg;
        ele2.innerHTML = newHtml;
        ele3.style.height = `${ele.offsetHeight}px`;
      },
    );
  }

  handleGeriskEventList = () => {
    this.props.dispatch({
      type: 'warningInfo/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/event/page',
        ...{
          curPage: 1,
          pageSize: 1000,
          enable: enums.riskEventEnable.effective.value,
        },
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          this.setState({
            riskEventList: response.data.rows,
          });
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };

  handleSubmit = msg => {
    const { changeEditModalVisible, editModalData } = this.props;
    const { riskEventUuid, warnMsg, keyWords } = this.state;
    if (!riskEventUuid) {
      message.error('风控触发事件不能为空');
      return;
    }
    if (!warnMsg.trim()) {
      message.error('预警信息不能为空');
      return;
    } else {
      if (warnMsg.length > 200) {
        message.error('预警信息不能超过200个字符');
        return;
      }
    }
    let falg = false;
    keyWords.map(keyWord => {
      const reg = new RegExp(`\\【${keyWord}\\】`, 'g');
      const count = warnMsg.trim().match(reg) || [];
      if (count.length != 1) {
        falg = true;
      }
    });
    if (falg) {
      message.error('预警信息格式不正确');
      return;
    }
    //TODO:请求接口
    this.setState({
      submitBtnLoading: true,
    });
    this.props.dispatch({
      type: 'warningInfo/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/warnMsg/save',
        uuid: editModalData.uuid,
        riskEventUuid: riskEventUuid,
        warnMsg: warnMsg.trim(),
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          changeEditModalVisible(true);
          // } else {
          //   message.error(response.statusMessage);
        }
        this.setState({
          submitBtnLoading: false,
        });
      },
    });
  };

  handleHtml = oldText => {
    const { keyWords } = this.state;
    let a = oldText;
    keyWords.map(str => {
      const tihan = `<span>【${str}】</span>`;
      const reg = new RegExp(`\\【${str}\\】`, 'g');
      a = a.replace(reg, tihan);
    });
    return a;
  };

  render() {
    const { submitBtnLoading, riskEventList, msg } = this.state;

    const { changeEditModalVisible } = this.props;

    return (
      <Modal
        title="修改预警信息"
        onCancel={() => changeEditModalVisible(false)}
        visible={true}
        footer={[
          <Button
            key="back"
            type="ghost"
            size="small"
            onClick={() => changeEditModalVisible(false)}
          >
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            size="small"
            loading={submitBtnLoading}
            onClick={() => this.handleSubmit()}
          >
            提交
          </Button>,
        ]}
      >
        <div className={styles.addModal}>
          <div className={styles.publicItem}>
            <div className={styles.itemTitle}>请选择风控触发事件:</div>
            <div className={styles.itemContent}>
              <Select
                disabled
                placeholder="请选择风控触发事件"
                defaultValue={this.props.editModalData.riskEventUuid}
                onChange={e => {
                  let findE = riskEventList.find(item => item.uuid === e);
                  const riskEventKey = Object.keys(enums.riskEventType).find(
                    item => enums.riskEventType[item].value === findE.riskEventType,
                  );
                  // console.log('enums.riskEventType', enums.riskEventType[riskEventKey]);
                  this.setState(
                    {
                      riskEventUuid: findE.uuid,
                      riskEventType: findE.riskEventType,
                      keyWords: enums.riskEventType[riskEventKey].keyWords,
                      msg: enums.riskEventType[riskEventKey].msg,
                      warnMsg: enums.riskEventType[riskEventKey].msg,
                    },
                    () => {
                      const ele = document.getElementById('text-area1');
                      const ele2 = document.getElementById('text-area2');
                      const ele3 = document.getElementById('text-Content');
                      const newHtml = this.handleHtml(enums.riskEventType[riskEventKey].msg);
                      ele.innerHTML = enums.riskEventType[riskEventKey].msg;
                      ele2.innerHTML = newHtml;
                      ele3.style.height = `${ele.offsetHeight}px`;
                    },
                  );
                }}
              >
                {riskEventList.map(e => {
                  return (
                    <Option key={e.uuid} value={e.uuid}>
                      {e.riskEventContent}
                    </Option>
                  );
                })}
              </Select>
            </div>
          </div>
          <div className={styles.publicItem}>
            <div className={styles.itemTitle}>请设置预警信息:</div>
            <div id="text-Content" className={styles.itemContent2}>
              <div
                className={styles.textContent1}
                onPaste={e => {
                  e.preventDefault();
                }}
                id="text-area1"
                onInput={() => {
                  const ele = document.getElementById('text-area1');
                  const ele2 = document.getElementById('text-area2');
                  const ele3 = document.getElementById('text-Content');
                  ele3.style.height = `${ele.offsetHeight}px`;
                  let oldHtml = ele.innerHTML;
                  const oldText = ele.innerText;
                  const reg1 = new RegExp('<span>', 'g');
                  const reg2 = new RegExp('</span>', 'g');
                  oldHtml = oldHtml.replace(reg1, '');
                  oldHtml = oldHtml.replace(reg2, '');
                  const newHtml = this.handleHtml(oldHtml);
                  ele2.innerHTML = newHtml;
                  this.setState({
                    warnMsg: oldText,
                  });
                }}
                contentEditable={true}
              ></div>
              <div
                onPaste={e => {
                  e.preventDefault();
                }}
                id="text-area2"
                className={styles.textContent2}
              ></div>
            </div>
          </div>
          <div className={styles.tipInfo}>
            如:
            {msg}
          </div>
        </div>
      </Modal>
    );
  }
}
